<?php
/**
 * 商户代偿（销账）功能开发
 */
namespace App\Http\Controllers\Collection;

use App\Constant\RepayConstant;
use App\Events\RepayMentEvent;
use App\Events\WithHoldEvent;
use App\Facades\MoneyPlatformRequestFacade;
use App\Jobs\RepayMoneyNotifyJobQueue;
use App\Models\Collection\RepayRecord as CollectionRepayRecordModel;
use App\Models\CollectionApiRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PayCompensateController extends BaseController
{
    /**
     * Description: 催收系统销帐
     * Author: Gxs
     * @return mixed
     */
    public function store()
    {
        $params = $this->pubData;
        $case_code = $params['caseCode'];
        $apply_number = $params['applyNumber'];
        Log::debug('pay_compensate_controller_params', ['params' => $params,]);
        $check_result = CollectionRepayRecordModel::checkWriteOffData($params);
        if (false == $check_result['status'])
            return collectionResp($check_result['response']);

        $summary_array = $check_result['summary_array'];
        $money_channel = $check_result['money_channel'];
        $repay_amount = $check_result['repay_amount'];
        try {
            $response = ['msg' => '成功','result' => CollectionApiRequest::RESPONSE_OK];
            DB::beginTransaction();
            foreach ($summary_array as $key=>$item) {
                $item['balance'] = $repay_amount;
                $item['apply_number'] = $apply_number;
                $item['last_period'] = $check_result['last_period'];
                switch ($money_channel) {
                    case RepayConstant::WRITE_OFF_ONE: //晋商
                    case RepayConstant::WRITE_OFF_TWO: //新光大
                        $result = CollectionRepayRecordModel::setCurrentPeriodWriteOff($item);
                        if ($result) {
                            $pay_compensate_result = MoneyPlatformRequestFacade::PayCompensate([
                                'loanId' => $case_code,
                                'currentPeriod' => $item['record_period']
                            ]);
                            if ($pay_compensate_result['flag']) {
                                $pay_compensate_result = $pay_compensate_result['result'];
                                //变更销帐状态为处理中
                                DB::table('repay_records')->where('id', $item['record_id'])->update([
                                    'xz_status' => CollectionRepayRecordModel::COMPENSATE_STATUS_TWO,
                                    'result_repay_id' => isset($pay_compensate_result['data']['resultRepayId']) ? $pay_compensate_result['data']['resultRepayId'] : '',
                                ]);
                            } else {
                                //变更销帐状态为失败
                                DB::table('repay_records')->where('id', $item['record_id'])->update([
                                    'xz_status' => CollectionRepayRecordModel::COMPENSATE_STATUS_THREE,
                                ]);
                            }
                        }
                        break;
                    case RepayConstant::WRITE_OFF_THREE: //老光大
                        $result = CollectionRepayRecordModel::setCurrentPeriodWriteOff($item);
                        if ($result) {
                            //变更销帐状态为成功
                            DB::table('repay_records')->where('id', $item['record_id'])->update([
                                'xz_status' => CollectionRepayRecordModel::COMPENSATE_STATUS_FOUR,
                            ]);
                            Log::debug('pay_compensate_notify_money_queue', ['record_id' => $item['record_id']]);
                            //主动还款通知资方
                            RepayMoneyNotifyJobQueue::dispatch($item['record_id']);
                        }
                        break;
                    case RepayConstant::WRITE_OFF_FOUR: //其他
                        $result = CollectionRepayRecordModel::setCurrentPeriodWriteOff($item);
                        if ($result) {
                            //变更销帐状态为成功
                            DB::table('repay_records')->where('id', $item['record_id'])->update([
                                'xz_status' => CollectionRepayRecordModel::COMPENSATE_STATUS_FOUR,
                            ]);
                        }
                        break;
                    default:
                        break;
                }
            }
            DB::commit();
            //催收回执
            event(new WithHoldEvent([
                'caseCode' => $case_code,
                'type' => RepayConstant::COLLECTION_BACK_TYPE_TWO,
                'applyNumber' => $apply_number,
                'state' => 4,
            ]));
            Log::debug('pay_compensate_controller_apply_number', ['apply_number' => $apply_number,]);
            //通知催收系统
            event(new RepayMentEvent($summary_array[0]['summary_id']));
            Log::debug('pay_compensate_controller_success', ['summary_id' => $summary_array[0]['summary_id'], 'params' => $params]);
        } catch (\Exception $e) {
            DB::rollBack();
            //催收回执
            event(new WithHoldEvent([
                'caseCode' => $case_code,
                'type' => RepayConstant::COLLECTION_BACK_TYPE_TWO,
                'applyNumber' => $apply_number,
                'state' => 3,
            ]));
            $response = ['msg' => '数据异常','result' => CollectionApiRequest::RESPONSE_OTHER_ERROR];
            Log::debug('pay_compensate_controller_exception', [
                'params' => $params,
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'message' => $e->getMessage(),
            ]);
        }
        return collectionResp($response);
    }
}
